import React, { useEffect, useState, useRef, useMemo } from "react";
import axios from "axios";
import { Link, useNavigate, useLocation } from "react-router-dom";
import './result.css';
import { Search } from 'react-vant';
import { ArrowLeft } from '@react-vant/icons';
import { VariableSizeList as List } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';

// 瀑布流列数和间距
const COLUMN_COUNT = 2;
const GAP = 16;

// 定义美妆数据接口
interface BeautyItem {
  name: string;
  content?: string;
  apply: string;
  imgs: string;
}

// Row 组件的 props 类型
interface RowProps {
  index: number;
  style: React.CSSProperties;
}

const Result: React.FC = () => {
  const [beautyList, setBeautyList] = useState<BeautyItem[]>([]);
  const [value, setValue] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(true);
  const navigate = useNavigate();
  const location = useLocation();
  const query = new URLSearchParams(location.search).get('query') || '';
  const listRef = useRef<List>(null);

  // 获取美妆数据
  const getBeautyData = async () => {
    try {
      setLoading(true);
      const res = await axios.post<{ list: BeautyItem[] }>('http://localhost:3000/auth/list');
      setBeautyList(res.data.list);
      setLoading(false);
    } catch (error) {
      console.error('Failed to fetch beauty data:', error);
      setLoading(false);
    }
  };

  useEffect(() => {
    getBeautyData();
  }, []);

  // 初始化搜索框的值
  useEffect(() => {
    if (query) {
      setValue(query);
    }
  }, [query]);

  // 缓存过滤数据
  const filteredList = useMemo(() => {
    return beautyList.filter(item =>
      item.name.toLowerCase().includes(value.toLowerCase())
    );
  }, [beautyList, value]);

  // 计算瀑布流每列的项数
  const itemCount = Math.ceil(filteredList.length / COLUMN_COUNT);

  // 计算每行的高度
  const getItemSize = (index: number): number => {
    const startIndex = index * COLUMN_COUNT;
    const items = filteredList.slice(startIndex, startIndex + COLUMN_COUNT);
    const maxHeight = items.reduce((max, _, idx) => {
      const imageHeight = 150 + ((startIndex + idx) % 3) * 50;
      const infoHeight = 60; // 预估文字区域高度
      return Math.max(max, imageHeight + infoHeight);
    }, 0);
    return maxHeight || 260; // 默认高度增加
  };

  // 渲染单行（包含两列）11111
  const Row = ({ index, style }: RowProps) => {
    const startIndex = index * COLUMN_COUNT;
    const items = filteredList.slice(startIndex, startIndex + COLUMN_COUNT);

    return (
      <div style={{ ...style, display: 'flex', justifyContent: 'space-between', padding: '0 8px' }}>
        {items.map((item, idx) => (
          <Link
            key={startIndex + idx}
            to={`/detail?name=${encodeURIComponent(item.name)}&content=${encodeURIComponent(item.content || '')}&apply=${encodeURIComponent(item.apply)}&imgs=${encodeURIComponent(item.imgs)}`}
            className="waterfall-item"
            style={{ width: `calc((100% - ${GAP}px) / ${COLUMN_COUNT})`, minHeight: '200px' }}
          >
            <div className="image-wrapper" style={{ height: 'auto' }}>
              <img
                src={item.imgs}
                alt={item.name}
                className="waterfall-item-image"
                style={{ height: `${150 + ((startIndex + idx) % 3) * 50}px` }}
                loading="lazy"
                onError={(e) => {
                  e.target.src = 'https://via.placeholder.com/150?text=Image+Failed';
                  console.log(`图片加载失败: ${item.imgs}`);
                }}
              />
            </div>
            <div className="waterfall-item-info">
              <span className="waterfall-item-name">{item.name}</span>
              <span className="waterfall-item-apply">{item.apply}</span>
            </div>
          </Link>
        ))}
        {items.length < COLUMN_COUNT &&
          Array(COLUMN_COUNT - items.length)
            .fill(null)
            .map((_, idx) => (
              <div
                key={`empty-${startIndex + idx}`}
                style={{ width: `calc((100% - ${GAP}px) / ${COLUMN_COUNT})` }}
              />
            ))}
      </div>
    );
  };

  // 处理搜索
  const handleSearch = (val: string) => {
    navigate(`/result?query=${encodeURIComponent(val)}`);
  };

  // 返回上一页
  const handleBack = () => {
    window.history.go(-1);
  };

  return (
    <div className="box">
      <div className="top" style={{ display: 'flex', alignItems: 'center', padding: '10px' }}>
        <ArrowLeft
          onClick={handleBack}
          style={{ marginRight: '12px', fontSize: '24px', cursor: 'pointer', color: '#333' }}
        />
        <Search
          value={value}
          onChange={setValue}
          onSearch={handleSearch}
          clearable
          placeholder="请输入搜索关键词"
          className="search-bar"
        />
      </div>
      <div className="list" style={{ height: 'calc(100vh - 60px)' }}>
        {loading ? (
          <div className="loading">加载中...</div>
        ) : filteredList.length > 0 ? (
          <AutoSizer>
            {({ height, width }) => (
              <List
                ref={listRef}
                height={height}
                width={width}
                itemCount={itemCount}
                itemSize={getItemSize}
                className="waterfall"
              >
                {Row}
              </List>
            )}
          </AutoSizer>
        ) : (
          <div className="no-data">暂无匹配数据</div>
        )}
      </div>
    </div>
  );
};

export default Result;